import React from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../store";
import { NavLink } from "react-router-dom";
import { SubmitBar } from "react-vant";
import {
  ProductCard,
  Tag,
  Button,
  Checkbox,
  Stepper,
  Dialog,
} from "react-vant";
import {
  addCarItemCountActionCreator,
  DeleteCarItemActionCreator,
  subCarItemCountActionCreator,
  switchAllISCheckedActionCreator,
  switchCarItemIsCheckedActionCreator,
} from "../../store/car/carActions";
import { useCar } from "../../hooks";

const Index: React.FC = () => {
  const car = useAppSelector((state) => state.car.car);
  const dispatch = useDispatch();
  const { selectPrice, allCheck } = useCar();
  if (car.length === 0) {
    return (
      <div>
        <NavLink to="/">购物车为空，赶紧来点东西吧</NavLink>
      </div>
    );
  }

  return (
    <div>
      <div className="car-list">
        {car.map((v) => {
          return (
            <div className="car-item" key={v.id}>
              <Checkbox
                checked={v.isChecked}
                onChange={() =>
                  dispatch(switchCarItemIsCheckedActionCreator(v.id))
                }
              ></Checkbox>
              <ProductCard
                num={
                  <Stepper
                    min={1}
                    value={v.count}
                    onPlus={() => dispatch(addCarItemCountActionCreator(v.id))}
                    onMinus={() => dispatch(subCarItemCountActionCreator(v.id))}
                    onOverlimit={() =>
                      Dialog.confirm({
                        title: "警告",
                        message: "再减少就要删除了！",
                      }).then(() => {
                        dispatch(DeleteCarItemActionCreator(v.id));
                      })
                    }
                  ></Stepper>
                }
                price={v.price}
                desc={v.desc}
                title={v.title}
                thumb={v.url}
              />
            </div>
          );
        })}
      </div>
      <SubmitBar price={selectPrice * 100} buttonText="提交订单">
        <Checkbox
          checked={allCheck}
          onChange={(val) => dispatch(switchAllISCheckedActionCreator(val))}
        >
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Index;
